﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using IFDB.Models.Contexts;
using IFDB.Models.Tables;
using IFDB.ViewModels.Foundation;
using IFDB.ViewModels.PartialViewModels;
using IFDB.ViewModels.PartialViewModels.Interfaces;

namespace IFDB.ViewModels.PageViewModels
{
    public class MatchViewModel : BaseViewModel
    {
        public MatchViewModel(Guid? matchId, int? page)
        {
            using (IFDBContext db = new IFDBContext())
            {
                Match = matchId != null 
                    ? db.Matches
                    .Include(m => m.Team1)
                    .Include(m => m.Team2)
                    .Include(m => m.Competition)
                    .Include(m => m.Venue)
                    .Single(m => m.MatchId == matchId)
                    : null;

                Team1Persons = db.AppearanceEvents
                    .Include(a => a.Person)
                    .Where(a => a.MatchId == matchId && a.TeamId == Match.Team1Id)
                    .OrderBy(a => a.MatchEventType)
                    .ThenBy(a => a.Minute)
                    .ThenBy(a => a.Plus)
                    .ThenBy(a => a.Person.Position)
                    .ToList()
                    .GroupBy(a => a.PersonId);

                Team2Persons = db.AppearanceEvents
                    .Include(a => a.Person)
                    .Where(a => a.MatchId == matchId && a.TeamId == Match.Team2Id)
                    .OrderBy(a => a.MatchEventType)
                    .ThenBy(a => a.Minute)
                    .ThenBy(a => a.Plus)
                    .ThenBy(a => a.Person.Position)
                    .ToList()
                    .GroupBy(a => a.PersonId);

                this.Page = (page ?? 1);
            }
        }

        

        public Match Match { get; private set; }

        public IEnumerable<IGrouping<Guid, AppearanceEvent>> Team1Persons { get; private set; }
        public IEnumerable<IGrouping<Guid, AppearanceEvent>> Team2Persons { get; private set; }
        public int Page { get; private set; }

        private IHeadToHeadViewModel headToHeadViewModel;
        public IHeadToHeadViewModel HeadToHeadViewModel
        {
            get
            {
                if (headToHeadViewModel == null)
                    headToHeadViewModel = new HeadToHeadViewModel(Match, Page);

                return headToHeadViewModel;
            }
        }

        private IDaysMatchesViewModel daysMatchesViewModel;
        public IDaysMatchesViewModel DaysMatchesViewModel
        {
            get
            {
                if (daysMatchesViewModel == null)
                    daysMatchesViewModel = new DaysMatchesViewModel(Match.MatchDate);

                return daysMatchesViewModel;
            }
        }

    }
}
